<template>
  <div class="profile">
    <el-tabs :tab-position="'left'" type="border-card" style="height: 700px" class="demo-tabs">
      <el-tab-pane :label="i18n.fy.gneralscenario">
        <el-row>
          <el-col :span="4">
            {{ i18n.fy.readprofile }}
          </el-col>
          <el-col :span="14"> </el-col>
          <el-col :span="4" style="text-align: right">
            <el-button type="primary" @click="send('readScene', '1')">
              {{ i18n.fy.sending }}
            </el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            {{ i18n.fy.switchprofile }}
          </el-col>
          <el-col :span="14">
            <el-select v-model="sceneSelect" class="m-2" :placeholder="i18n.language == 'zh-cn'
      ? '请选择情景模式'
      : 'Please select a profile'
      ">
              <el-option v-for="item in sceneOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
          <el-col :span="4" style="text-align: right">
            <el-button type="primary" @click="send('callScene', sceneSelect)">
              {{ i18n.fy.sending }}</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <p style="color: rgb(217, 150, 0); font-size: 14px">
              {{ i18n.fy.rcbatslgze }}
            </p>
          </el-col>
        </el-row>
      </el-tab-pane>
      <!-- 定时情景 -->
      <el-tab-pane :label="i18n.fy.timedccenario">
        <el-row v-show="sceneVisible">
          <el-col :span="4">
            {{
      i18n.language == "zh-cn" ? "定时情景列表" : "Timed Scenario List"
    }}
          </el-col>
          <el-col :span="20" style="text-align: right">
            <el-button type="primary" @click="addScene()">
              {{
      i18n.language == "zh-cn"
        ? "新增定时情景"
        : "Add timed scenarios"
    }}
            </el-button>
          </el-col>
        </el-row>
        <el-row v-show="sceneVisible" style="border-bottom: 0">
          <el-col :span="24">
            <div>
              <el-table :empty-text="i18n.fy.nodata" :data="sceneTableData" style="height: 450px"
                class="scene-table-cls">
                <el-table-column prop="ruleTitle" :label="i18n.language == 'zh-cn' ? '任务名称' : 'TASK'" />
                <el-table-column prop="startTime" :label="i18n.language == 'zh-cn' ? '执行时间' : 'execution time'
      " width="180">
                  <template #default="scope">
                    <div v-html="showTime(scope.row)"></div>
                  </template>
                </el-table-column>
                <el-table-column prop="name" :label="i18n.language == 'zh-cn' ? '调用情景' : 'Call scenario'
      " width="140">
                  <template #default="scope">
                    {{ showScope(scope.row) }}
                  </template>
                </el-table-column>
                <el-table-column prop="name" :label="i18n.language == 'zh-cn' ? '灯组' : 'Lamp group'">
                  <template #default="scope">
                    <p class="operateInfo" v-for="(item, i) in showOper(scope.row.operateInfo)">
                      {{ item.area }}区
                      <span v-if="item.code != '400'">{{ item.address }}</span>
                      <span v-if="item.code == '200'">组</span>
                      <span v-if="item.code == '300'">标签</span>
                      <span v-if="item.code == '100' || item.code == '10'">号</span>
                    </p>
                  </template>
                </el-table-column>
                <el-table-column prop="name" :label="i18n.fy.操作" align="center" width="190">
                  <template #default="scope">
                    <el-button link type="primary" @click="testScen(scope.row)" v-if="enable">
                      {{ i18n.language == "zh-cn" ? "测试" : "test" }}
                    </el-button>
                    <el-button link type="primary" @click="editScen(scope.row)">
                      {{ i18n.language == "zh-cn" ? "编辑" : "edit" }}
                    </el-button>
                    <el-button link type="primary" @click="changeEnableState(scope.row, 1)"
                      v-if="scope.row.enableState == '0'">
                      {{ i18n.language == "zh-cn" ? "启用" : "Enable" }}
                    </el-button>
                    <el-button link type="danger" @click="changeEnableState(scope.row, 0)"
                      v-if="scope.row.enableState == '1'">
                      {{ i18n.language == "zh-cn" ? "停用" : "Deactivate" }}
                    </el-button>
                    <el-button link type="danger" @click="delScen(scope.row)">
                      {{ i18n.language == "zh-cn" ? "删除" : "delete" }}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>

        <el-row v-show="!sceneVisible">
          <div class="sceneVisible">
            <el-col :span="24">
              <div class="newName">
                <span>{{ i18n.fy.taskname }}</span>
                <el-input v-model="scenModel.data.ruleTitle" placeholder="请输入" style="width: 220px" />
              </div>
            </el-col>
            <el-col :span="24">
              <div class="newName">
                <span>{{ i18n.fy.executionmode }}</span>
                <div>{{ scenModel.data.chooseWorkDay }}</div>
                <div>{{ carryOptions[0].value === scenModel.data.chooseWorkDay }}</div>
                <el-select @change="(val) => changeWorkDay(val)" style="width: 220px" multiple
                  v-model="scenModel.data.chooseWorkDay" class="m-2" placeholder="请选择情景模式">
                  <el-option v-for="(item, i) in carryOptions" :key="'zxms_' + i" :label="item.label"
                    :value="item.value" />
                </el-select>
                <span>{{ i18n.fy.executiontime }}</span>
                <el-time-picker style="width: 220px" format="HH:mm" data-format="HH:mm" value-format="HH:mm"
                  v-model="scenModel.data.startTime" placeholder="任意时间点" />
              </div>
            </el-col>
            <el-col :span="24">
              <div class="newName">
                <span>{{ i18n.fy.callingscenario }}</span>
                <el-select style="width: 220px" v-model="transferScene" class="m-2" placeholder="">
                  <el-option v-for="item in sceneOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="lamp-group-label">
                <div class="newName">
                  <span>{{ i18n.fy.controlthelightgroup }}</span>
                </div>
                <p class="altconp">
                  <span class="altcon" v-for="(item, i) in operateList" @click="deleteTag(i)">
                    {{ item.area }}区
                    <span v-if="item.code != '400'">{{ item.address }}</span>
                    <span v-if="item.code == '200'">组</span>
                    <span v-if="item.code == '300'">标签</span>
                    <span v-if="item.code == '100' || item.code == '10'">号</span>
                  </span>
                  <el-button style="margin-left:5px;" type="primary" @click="addingLamp()">新增灯</el-button>
                </p>
              </div>
            </el-col>
            <el-col :span="24" style="text-align: center">
              <el-button type="primary" @click="submitScen()">提交定时情景</el-button>
              <el-button type="" @click="sceneVisible = true">返回</el-button>
            </el-col>
          </div>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <el-dialog v-model="lampVisible" draggable title="新增灯具" width="40%" class="">
      <div style="padding-bottom: 30px">
        <div class="top">
          <el-row>
            <el-col :span="4">
              <el-select clearable style="width: 120px" v-model="typeOpt" class="m-2" placeholder="">
                <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>

            <el-col :span="5" v-if="typeOpt != 10">
              <span>{{ i18n.fy.gateways }}</span>
              <el-select clearable v-model="gateway_1" class="m-2" placeholder="">
                <el-option :label="i18n.fy.allgateways" :value="''" />
                <el-option v-for="item in gatewayList" :key="item.id" :label="item.nickName" :value="item.id" />
              </el-select>
            </el-col>
            <el-col :span="4" v-if="typeOpt != 10">
              <span>区</span>
              <el-select clearable v-model="district_1" :placeholder="i18n.language == 'zh-cn' ? '区' : 'distinguish'">
                <el-option v-for="item in deviceAreaAllList" :value="item.area_code">
                  {{ item.area_code }}
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="8" v-if="typeOpt == 200 && typeOpt != 10">
              <span>组</span>
              <el-select clearable v-model="group_1" placeholder="" multiple filterable>
                <el-option v-for="item in options" :value="item.group_name" v-show="item.group_name != '全部'">
                  {{ item.group_name }}
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4" v-if="typeOpt == 100 && typeOpt != 10">
              <span>号</span>
              <el-input v-model="num_1" placeholder="" />
            </el-col>
            <el-col :span="4" v-if="typeOpt == 300 && typeOpt != 10">
              <span>标签</span>
              <el-input v-model="num_tag" placeholder="" />
            </el-col>
          </el-row>
        </div>
        <el-table :empty-text="i18n.fy.nodata" v-if="typeOpt == 10" :data="data.tableData" style="height: 400px"
          class="sceneTableData" @selection-change="handleSelectionChange3" ref="multipleSelection3Tab">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="areaCode" label="区" />
          <el-table-column prop="groupName" label="组"> </el-table-column>
          <el-table-column prop="deviceIndex" label="号"> </el-table-column>
          <el-table-column prop="ramk" label="备注"> </el-table-column>
          <el-table-column prop="pwd" label="网络密码" width="240">
            <template #default="scope">
              <el-input v-model="scope.row.pwd" placeholder="请输入网络密码" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="enterOs()">确认</el-button>
          <el-button @click="lampVisible = false"> 取消 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { i18nStore } from "@/pinia/i18n";
const i18n = i18nStore();
import { wirelessManageStore } from "@/pinia/wirelessManage";
const wmStore = wirelessManageStore();
import { getAllDeviceTimingList, testTimingInterface } from "@/api/wirelessmanageApi";


const sceneTableData = ref([]);
const isEdit = ref(false);
const emits = defineEmits(['DeleteTag', 'AddingLamp'])

watch(
  () => wmStore.timedScenarioObj,
  (newValue, oldValue) => {
    sceneTableData.value = wmStore.operateObjList;
  }
);

let sceneSelect = ref("");
let sceneOptions = ref([
  { value: 1, label: "场景1" },
  { value: 2, label: "场景2" },
  { value: 3, label: "场景3" },
  { value: 4, label: "场景4" },
  { value: 5, label: "场景5" },
  { value: 6, label: "场景6" },
  { value: 7, label: "场景7" },
  { value: 8, label: "场景8" },
  { value: 9, label: "场景9" },
  { value: 10, label: "场景10" },
  { value: 11, label: "场景11" },
  { value: 12, label: "场景12" },
]);
let sceneVisible = ref(true);
let enable = ref(true);
let scenModel = reactive({ data: { chooseWorkDay: "1,2,3,4,5,6,7" } });
let carryOptions = ref([
  { value: "1,2,3,4,5,6,7", label: "每天执行" },
  { value: "1", label: "每周一执行" },
  { value: "2", label: "每周二执行" },
  { value: "3", label: "每周三执行" },
  { value: "4", label: "每周四执行" },
  { value: "5", label: "每周五执行" },
  { value: "6", label: "每周六执行" },
  { value: "7", label: "每周日执行" },
]);
let transferScene = ref("");
let operateList = ref([]);
// 新增灯具
let lampVisible = ref(false);

const testScen = async (row) => {
  wmStore.setOperateItem(row)
  const data = await testTimingInterface(JSON.parse(JSON.stringify(row)));
  if (data.code === 200) {
    ElMessage.success(data.message)
  } else {
    ElMessage.error(data.message)
  }
};

// 编辑
const editScen = (row) => {
  sceneVisible.value = false;
  isEdit.value = false;
  wmStore.setOperateItem(row)
  scenModel.data = JSON.parse(JSON.stringify(row));
  console.log('scenModel.data', scenModel.data);
  operateList.value = JSON.parse(JSON.stringify(wmStore.operateItem.operateInfoObj));
};

const changeWorkDay = (val) => {
  // if (
  //   scenModel.data.chooseWorkDay[scenModel.data.chooseWorkDay.length - 1] ==
  //   "1,2,3,4,5,6,7"
  // ) {
  //   scenModel.data.chooseWorkDay = ["1,2,3,4,5,6,7"];
  // } else {
  //   var i = scenModel.data.chooseWorkDay.indexOf("1,2,3,4,5,6,7");
  //   if (i >= 0) {
  //     scenModel.data.chooseWorkDay.splice(i, 1);
  //   }
  // }
};

const submitScen = () => {
  if (scenModel.data.ruleTitle == undefined || scenModel.data.ruleTitle == "") {
    ElMessage.error("任务名称不能为空！");
    return;
  }
  if (
    scenModel.data.operateInfo == undefined ||
    scenModel.data.operateInfo.length == 0
  ) {
    ElMessage.error("操作灯组不能为空！");
    return;
  }
  let obj = JSON.parse(
    JSON.stringify({
      deviceFid: pid.value,
      deviceTimingRule: scenModel.data,
    })
  );
  for (let i = 0; i < obj.deviceTimingRule.operateInfo.length; i++) {
    obj.deviceTimingRule.operateInfo[i].params = transferScene.value;
  }
  obj.deviceTimingRule.operateInfo = JSON.stringify(
    obj.deviceTimingRule.operateInfo
  );
  let urls = "/deviceTimingRule/update";
  if (isEdit) {
    obj.deviceTimingRule.enableState = 1;
    urls = "/deviceTimingRule/addMeshTimingRule";
  } else {
    urls = "/deviceTimingRule/update";
  }
  let arr = JSON.parse(JSON.stringify(obj.deviceTimingRule.chooseWorkDay));
  obj.deviceTimingRule.chooseWorkDay =
    obj.deviceTimingRule.chooseWorkDay.toString();
  $axios
    .post(urls, obj)
    .then((res) => {
      if (res.data.code === 200) {
        layer.msg(`保存成功`, { time: 500 });
        sceneVisible.value = true;
        getTabTimingList();
      }
    })
    .catch((err) => { });
};

const changeEnableState = (row, num) => {
  let params = JSON.parse(JSON.stringify(row));
  params.enableState = num;
  params.operateInfo = JSON.stringify(params.operateInfo);
  let obj = { deviceFid: pid.value, deviceTimingRule: params };
  obj.deviceTimingRule.chooseWorkDay =
    obj.deviceTimingRule.chooseWorkDay.toString();
  $axios
    .post("/deviceTimingRule/update", obj)
    .then((res) => {
      if (res.data.code === 200) {
        let tips = "";
        if (num == 0) {
          tips = "停用";
        } else {
          tips = "启用";
        }
        layer.msg(tips + `成功`, { time: 500 });
        getTabTimingList();
      }
    })
    .catch((err) => { });
};

const delScen = (row) => {
  if (row.enableState == 1) {
    layer.msg("请先停用再做删除操作！");
    return;
  }
  ElMessageBox.confirm("确认删除?", "提示")
    .then(() => {
      let params = { id: row.id };
      const formData = new FormData();
      formData.append("id", row.id);
      $axios
        .post("/deviceTimingRule/deleteTimingRule", formData)
        .then((res) => {
          if (res.data.code === 200) {
            layer.msg("删除成功！");
            getTabTimingList();
          } else {
            layer.msg("删除失败!");
          }
        });
    })
    .catch(() => { }); // 新增错误捕获
};

const addScene = () => {
  sceneVisible.value = !sceneVisible.value;
  scenModel.data = {
    chooseWorkDay: [],
    startTime: "08:00",
    operateInfo: [],
  };
  carryvalue.value = "";
  transferScene.value = 1;
  isEdit.value = true;
};

const showScope = (row) => {
  if (row.operateInfo && row.operateInfo.length > 0) {
    let obj = sceneOptions.value.filter((item) => {
      if (typeof row.operateInfo === "string") {
        return JSON.parse(row.operateInfo)[0].params == item.value;
      }
      return row.operateInfo[0].params == item.value;
    });
    if (obj.length > 0 && obj[0].label) {
      return obj[0].label;
    }
  }
};

const showTime = (row) => {
  if (row.chooseWorkDay == "1,2,3,4,5,6,7") {
    return `<div>每天${row.startTime}执行</div>`;
  }
  let arr = [];
  if (row.chooseWorkDay.length > 1 && !(row.chooseWorkDay instanceof Array)) {
    arr = row.chooseWorkDay.split(",");
  } else if (row.chooseWorkDay.length == 1) {
    arr = [row.chooseWorkDay];
  } else {
    arr = row.chooseWorkDay;
  }
  let str = "";
  for (let i = 0; i < arr.length; i++) {
    let wek = arr[i];
    if (arr[i] == 1) {
      wek = "一";
    } else if (arr[i] == 2) {
      wek = "二";
    } else if (arr[i] == 3) {
      wek = "三";
    } else if (arr[i] == 4) {
      wek = "四";
    } else if (arr[i] == 5) {
      wek = "五";
    } else if (arr[i] == 6) {
      wek = "六";
    } else if (arr[i] == 7) {
      wek = "日";
    }
    if (wek) {
      str += `<div>每周${wek}${row.startTime}执行</div>`;
    }
  }
  return str;
};

const showOper = (strt) => {
  if (strt == undefined) {
    return "";
  } else if (typeof strt === "string") {
    return JSON.parse(strt);
  } else {
    return strt;
  }
};

const deleteTag = (i) => {
  ElMessageBox.confirm("是否删除此条记录?", "提示").then(() => {
    scenModel.data.operateInfo.splice(i, 1);
  });
};

const addingLamp = () => {
  lampVisible.value = true;
};

defineExpose({})
</script>

<style lang="scss" scoped>
.profile {}
</style>
